package mspbots.cw.data.core.boards;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.cw.common.ResultMsg;
import mspbots.cw.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class BoardAutoAssignResourceReceiver extends AbstractToolsUtil {

    private final BoardAutoAssignResourceRepository boardAutoAssignResourceRepository;

    @RabbitListener(queues = "connect-wise.board-auto-assign-resource.sync")
    public void processMsg(ResultMsg resultMsg) {
        BoardAutoAssignResource data = BoardAutoAssignResource.builder().otherId(resultMsg.getId()).build();
        data.setTenantId(resultMsg.getTenantId());
        data.setExtend(resultMsg.getEntity());
        data.setSyncTime(resultMsg.getSyncDate());
        data.setUpdateTime(LocalDateTime.parse(resultMsg.getEntity().findValue("lastUpdated").textValue(),
                DateTimeFormatter.ISO_ZONED_DATE_TIME));

        this.boardAutoAssignResourceRepository.findByOtherIdAndTenantId(resultMsg.getId(), resultMsg.getTenantId())
                .map(result -> {
                    data.setId(result.getId());
                    return data;
                })
                .defaultIfEmpty(data)
                .flatMap(this.boardAutoAssignResourceRepository::save).block(Duration.ofSeconds(10));

    }
}
